package maple.thelittleredbook.recommendation.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Select;
import maple.thelittleredbook.recommendation.entity.ContentFeature;

import java.math.BigDecimal;
import java.util.List;

/**
 * 内容特征Mapper接口
 */
@Mapper
public interface ContentFeatureMapper extends BaseMapper<ContentFeature> {

    /**
     * 获取失败任务数量
     *
     * @return 失败任务数量
     */
    @Select("SELECT COUNT(*) FROM content_features WHERE task_status = 'FAILED'")
    Long getFailedTaskCount();

    /**
     * 获取所有待处理任务
     *
     * @return 待处理任务列表
     */
    @Select("SELECT * FROM content_features WHERE task_status = 'PENDING' ORDER BY created_at ")
    List<ContentFeature> selectPendingTasks();

    /**
     * 批量重置失败任务状态为待处理
     *
     * @return 更新的记录数
     */
    @Update("UPDATE content_features SET task_status = 'PENDING', " +
            "task_started_at = NULL, task_completed_at = NULL, error_message = NULL, " +
            "updated_at = NOW() " +
            "WHERE task_status = 'FAILED'")
    int resetFailedTasks();

    /**
     * 原子性锁定单个任务
     *
     * @param id 任务ID
     * @return 更新的记录数（1表示锁定成功，0表示锁定失败）
     */
    @Update("UPDATE content_features SET task_status = 'PROCESSING', " +
            "task_started_at = NOW(), retry_count = retry_count + 1, updated_at = NOW() " +
            "WHERE id = #{id} AND task_status = 'PENDING'")
    int lockSingleTask(@Param("id") Long id);

    /**
     * 更新任务完成状态和特征值
     *
     * @param id 任务ID
     * @param dim1-dim8 特征值
     * @return 更新的记录数
     */
    @Update("UPDATE content_features SET " +
            "task_status = 'COMPLETED', task_completed_at = NOW(), " +
            "dim1 = #{dim1}, dim2 = #{dim2}, dim3 = #{dim3}, dim4 = #{dim4}, " +
            "dim5 = #{dim5}, dim6 = #{dim6}, dim7 = #{dim7}, dim8 = #{dim8}, " +
            "updated_at = NOW() " +
            "WHERE id = #{id}")
    int updateTaskCompleted(@Param("id") Long id,
                            @Param("dim1") BigDecimal dim1,
                            @Param("dim2") BigDecimal dim2,
                            @Param("dim3") BigDecimal dim3,
                            @Param("dim4") BigDecimal dim4,
                            @Param("dim5") BigDecimal dim5,
                            @Param("dim6") BigDecimal dim6,
                            @Param("dim7") BigDecimal dim7,
                            @Param("dim8") BigDecimal dim8);

    /**
     * 更新任务失败状态
     *
     * @param id 任务ID
     * @param errorMessage 错误信息
     * @return 更新的记录数
     */
    @Update("UPDATE content_features SET task_status = 'FAILED', " +
            "task_completed_at = NOW(), error_message = #{errorMessage}, updated_at = NOW() " +
            "WHERE id = #{id}")
    int updateTaskFailed(@Param("id") Long id, @Param("errorMessage") String errorMessage);

    /**
     * 根据内容ID获取已完成的内容特征
     *
     * @param contentId 内容ID
     * @return 已完成的内容特征，如果不存在或未完成则返回null
     */
    @Select("SELECT * FROM content_features WHERE content_id = #{contentId} AND task_status = 'COMPLETED'")
    ContentFeature selectCompletedFeatureByContentId(@Param("contentId") Long contentId);

    /**
     * 重置指定内容的特征状态为待处理
     * 当内容文本发生变化时使用
     *
     * @param contentId 内容ID
     * @return 更新的记录数
     */
    @Update("UPDATE content_features SET task_status = 'PENDING', " +
            "task_started_at = NULL, task_completed_at = NULL, error_message = NULL, " +
            "retry_count = 0, updated_at = NOW() " +
            "WHERE content_id = #{contentId}")
    int resetContentFeatureToPending(@Param("contentId") Long contentId);

    /**
     * 应用启动时重置异常中断的处理任务
     *
     * @return 更新的记录数
     */
    @Update("UPDATE content_features SET task_status = 'PENDING', " +
            "task_started_at = NULL, updated_at = NOW() " +
            "WHERE task_status = 'PROCESSING'")
    int resetProcessingTasks();
}